import {Body, Injectable, Logger} from "@nestjs/common";
import {SocketClientService} from "./services/socket-client/socket-client.service";
import {
    ErrorResponse,
    MapRes,
    SuccessResponse,
} from "../../system-server/src/types/types";
import {LogService} from "@app/log";
import {OnEvent} from "@nestjs/event-emitter";
import {EnumEvents} from "../../../types/constants";

@Injectable()
export class BreathServerService {
    constructor(
        private readonly sockClientService: SocketClientService,
        private readonly logger: LogService,
    ) {
    }

    getHello(): string {
        return "Hello World!";
    }

    async connectBreathServer() {
        try {
            await this.sockClientService.connect();
            return MapRes.success();
        } catch (e) {
            return MapRes.error({
                msg: "呼吸设备连接失败",
            });
        }
    }

    close() {
        this.sockClientService.close();
        return MapRes.success();
    }

    modifyFilter(filterCondition, initFlag) {
        this.sockClientService.modifyFilter(filterCondition, initFlag);
        return MapRes.success();
    }

    recordStart() {
        this.sockClientService.recordStart();
        return MapRes.success();
    }

    scanStart() {
        this.sockClientService.scanStart();
        return MapRes.success();
    }

    scanEnd() {
        this.sockClientService.scanEnd();
        return MapRes.success();
    }

    recordEnd() {
        const recordArr = this.sockClientService.recordEnd();
        this.logger.log({
            recordArr: recordArr,
        });
        return MapRes.success({
            data: recordArr,
        });
    }

    getBreathInfo() {
        return MapRes.success({
            data: this.sockClientService.breathInfo.breathFrequency,
        });
    }

    setAmplitude(amplitude: number) {
        this.sockClientService.setAmplitude(amplitude);
    }

    async getRecent() {
        try {
            const recentData = this.sockClientService.getRecent();
            return MapRes.success({
                data: recentData,
            });
        } catch (e) {
            return MapRes.error();
        }
    }

    @OnEvent(EnumEvents.breathClientDisconnect)
    handleClientDisconnected() {
        console.log(`收到breath客户端断开连接消息，关闭`);
        this.close()
    }
}
